package com.ones.kit.excel.handler;

import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import cn.idev.excel.exception.ExcelDataConvertException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Excel analysis EventListener
 *
 * @author Clark
 * @version 2025-03-18
 */
@Slf4j
public class ExcelAnalysisEventListener<T> extends AnalysisEventListener<T> {

    private final List<T> list = new ArrayList<>();

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败: {}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException ex = (ExcelDataConvertException) exception;
            log.error("第 {} 行, 第 {} 列解析异常, 数据: {}", ex.getRowIndex(), ex.getColumnIndex(), ex.getCellData());
        }
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        log.debug("解析到一条数据: {}", data.toString());
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.debug("所有数据解析完成！");
    }

    public List<T> getList() {
        return list;
    }
}
